<template>
  <div class="sheet-fun">
    <el-alert
      title="此方法为纯前端导出excel方法，适用于小数据量单独完成业务功能使用，更多时候需要配合后端，这里只是提供一种便捷的解决方案，详细使用请参看源码"
      type="success"
    ></el-alert>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>前端导出</span>
        </div>
      </template>
      <div>
        sheetjs官网：<a href="https://sheetjs.com/" target="_blank"
          >https://sheetjs.com/</a
        >
      </div>
      <div>
        官方demo：<a href="https://oss.sheetjs.com/sheetjs/" target="_blank"
          >https://oss.sheetjs.com/sheetjs/</a
        >
      </div>
      <div>
        gitHub:
        <a href="https://github.com/SheetJS/sheetjs" target="_blank"
          >https://github.com/SheetJS/sheetjs</a
        >
      </div>

      <div>
        本例参考链接：<a
          href="http://blog.haoji.me/js-excel.html"
          target="_blank"
          >http://blog.haoji.me/js-excel.html</a
        >
      </div>
    </el-card>

    <div class="export">
      <el-button @click="exportCommon">普通表格导出</el-button>
      <el-button @click="exportMerge">带合并单元格导出</el-button>
      <el-button @click="exportSheetMul"
        >多个sheet合并到一个excel导出</el-button
      >
    </div>
  </div>
</template>

<script setup>
// {openDownloadDialog,
//   sheet2blob,
//   arr2sheet}
import {
  openDownloadDialog,
  sheet2blob,
  arr2sheet,
} from "@/utils/xlsxUtils.js";
import { ref } from "vue";

function exportCommon() {
  const data = [
    ["姓名", "性别", "年龄", "注册时间"],
    ["张三", "男", 18, "2023-01-01"],
    ["李四", "女", 22, "2023-01-01"],
  ];
  var sheet = arr2sheet(data); // 数据转成sheet
  openDownloadDialog(sheet2blob([sheet]), "导出的文件名.xlsx");
}

function exportMerge() {
  const data = [
    ["合并后保留的信息", "要合并的cell占坑", "要合并的cell占坑", "其它信息"], // 特别注意合并的地方要占坑,要合并的第一个单元格的内容为合并后的内容
    ["姓名", "性别", "年龄", "注册时间"],
    ["张三", "男", 18, "2023-01-01"],
    ["李四", "女", 22, "2023-01-01"],
  ];
  const merges = [
    // 设置A1-C1的单元格合并 s：合并的起始cell，e:合并的终止cell , r:cell的row, c:cell的col
    { s: { r: 0, c: 0 }, e: { r: 1, c: 2 } },
  ];
  var sheet = arr2sheet(data, merges); // 数据转成sheet
  openDownloadDialog(sheet2blob([sheet]), "导出的文件名-合并单元格.xlsx");
}

function exportSheetMul() {
  const data = [
    ["姓名", "性别", "年龄", "注册时间"],
    ["张三", "男", 18, "2023-01-01"],
    ["李四", "女", 22, "2023-01-01"],
  ];
  var sheet = arr2sheet(data); // 数据转成sheet
  openDownloadDialog(sheet2blob([sheet, sheet]), "导出的文件名-多个sheet.xlsx");
}

// exportExcelExample();
</script>

<style lang="scss" scoped>
.sheet-fun {
  padding: 10px;
  .box-card {
    margin: 10px 0;
    color: #777;
    .card-header {
      font-size: 20px;
    }
  }
}
.export {
}
pre {
  background-color: #eee;
}
</style>
